package com.jamal2362.apktool.util.search;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class SearchUtils
{
	public static boolean indexOf(File file, String need, boolean ignoreCase)
	{
		try
		{
			String  line;
			String[] needle = need.split("\n");
			int count = 0;
			FileInputStream fis = new FileInputStream(file);
			BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
			while ((line = reader.readLine()) != null)
			{
				if (needle.length == 1)
				{
					if (indexOfIgnore(line, need, ignoreCase))
						return true;
				}
				else
				{
					if (count == 0)
					{
						if (ends(line, needle[count], ignoreCase))
							count++;
					}
					else
					{
						if (count < needle.length - 1)
						{
							if (equals(line, needle[count], ignoreCase))
								count++;
							else
								count = 0;
						}
						else
						{
							if (starts(line, needle[count], ignoreCase))
								return true;
							else
								count = 0;
						}
					}
				}
			}
		}
		catch (Exception e)
		{
		}
		return false;
	}

	public static boolean indexOfIgnore(String haystack, String need, boolean ignoreCase)
	{
		if (ignoreCase)
		{
			return haystack.toLowerCase().indexOf(need.toLowerCase()) >= 0;
		}
		else
		{
			return haystack.indexOf(need) >= 0;
		}
	}

	public static boolean equals(String haystack, String need, boolean ignoreCase)
	{
		if (ignoreCase)
		{
			return haystack.equalsIgnoreCase(need);
		}
		else
		{
			return haystack.equals(need);
		}
	}

	public static boolean starts(String haystack, String need, boolean ignoreCase)
	{
		if (ignoreCase)
		{
			return haystack.toLowerCase().startsWith(need.toLowerCase());
		}
		else
		{
			return haystack.startsWith(need);
		}
	}

	public static boolean ends(String haystack, String need, boolean ignoreCase)
	{
		if (ignoreCase)
		{
			return haystack.toLowerCase().endsWith(need.toLowerCase());
		}
		else
		{
			return haystack.endsWith(need);
		}
	}
}
